<template>
	<view>
		<!-- 
		  授权页面 
		  用到button 的open-type里面的 getUserInfo的开发能力
		  https://developers.weixin.qq.com/miniprogram/dev/component/button.html
		 -->

		<view class="auth">
			<button type="primary" plain @tap="handleUserInfo">
				获取用户授权
			</button>
		</view>
	</view>
</template>

<script>
	import { login } from "@/utils/asyncWx.js"
	export default {
		data() {
			return {

			}
		},
		methods: {
			handleUserInfo: function() {
				console.log(123)
				// https://uniapp.dcloud.net.cn/api/plugins/login?id=getuserprofile
				uni.getUserProfile({
					desc: "描述",
					success: async (result) =>{
						try {
							//通过button 获取到的参数信息
							// encryptedData, iv, rawData, signature
							let {
								encryptedData,
								iv,
								rawData,
								signature
							} = result;
							//通过 uni.login 获取 code 参数
							// https://uniapp.dcloud.net.cn/api/plugins/login?id=login
							let {
								code
							} = await login();
							//console.log(code);
							//发请求 获取token 数据 
							const res = await this.$request({
								url: "/users/wxlogin",
								method: "POST", //post
								data: {
									encryptedData,
									iv,
									rawData,
									signature,
									code
								}
							});
							//存到本地缓存中
							uni.setStorageSync("token", res.token);
							//返回上一个页面
							uni.navigateBack({
								delta: 1
							})
						} catch (e) {
							console.log(e);
						}
					}
				})
			}
		}
	}
</script>

<style>

</style>
